const glob = require('glob')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const entry = {} // 入口
const htmlplugins = [] // html
const files = glob.sync('./src/pages/*/main.js') // 目录结构

files.forEach(file => {
  const page = file.split('/')[3] // 页面
  entry[page] = ['babel-polyfill', file] // 生成入口
  htmlplugins.push(new HtmlWebpackPlugin({
    template: './public/index.html',
    filename: `${page}/index.html`,
    title: page,
    chunks: [page]
  }))
})

if (htmlplugins.length > 0) {
  const options = JSON.parse(JSON.stringify(htmlplugins[0].options))
  options.filename = 'index.html'
  htmlplugins.push(new HtmlWebpackPlugin(options))
}

module.exports = {
  entry,
  output: {
    filename: '[name].[hash:8].js'
    // publicPath: process.env.NODE_ENV === 'production' ? 'http://zhkumsg.gitee.io/webpack-multiple/' : ''
  },
  mode: process.env.NODE_ENV,
  module: {
    rules: [
      {
        test: /\.(png|jpg|jpeg|gif)$/i,
        use: 'file-loader'
      },
      {
        test: /\.less$/i,
        use: [MiniCssExtractPlugin.loader, { loader: 'css-loader' }, { loader: 'less-loader' }]
      },
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, { loader: 'css-loader' }]
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: [{ loader: 'babel-loader' }, { loader: 'eslint-loader' }]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[hash:8].css'
    }),
    ...htmlplugins,
    new CleanWebpackPlugin()
  ],
  devServer: {
    contentBase: './dist/'
  }
}
